from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Collect
from .models import Good
from decorator.decorator import check_login
from .serializer import CollectSer


# 商品收藏

class CollectAPIView(APIView):
    @check_login
    def post(self,request):

        # 1.获取前端数据 ， token， 商品productID
        good_id = request.data.get('productID')
        user = request.user

        # # 2.根据token  判断是否登录
        # if not token:
        #     return Response({'code':203, 'msg':'用户未登录'})
        #      # 已登录 ，则获取payload中的username ，根据用户查询对象
        #      # 未登录， 直接返回响应未登录
        # try:
        #     payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms='HS256')
        # except:
        #     return Response({"code":204, 'msg':'历史签名过期，需重新登录'})
        #
        #
        # # 3. 根据productID查询商品对象
        # username = payload.get('username')
        # user = User.objects.get(username=username)


        good = Good.objects.get(id=good_id)
        # 4. 创建收藏对象，存储收藏数据
        # 需要判断
        if Collect.objects.filter(user=user, good=good).count() != 0:
            return Response({'code':204, 'msg':'该商品已收藏'})
        # 创建收藏对象，存储收藏数据
        Collect.objects.create(user=user,good=good)
        # 5.返回成功添加响应
        return Response({"code":200, 'msg':'收藏成功'})

    @check_login
    def get(self,request):

        # 1.获取用户对象
        user = request.user

        # 2.根据用户对象，查询其收藏的商品对象
        collect_queryset = Collect.objects.filter(user=user)


        # 3.组织收藏数据结果，主页不能直接序列化
        # data = CollectSer(collect_queryset, many=True)
        #         # print("XXXX:", data.data)

        # 前端需要的数据 结构
        collect_list = []
        for i in collect_queryset:
            temp = {
                "id": i.good.id,
                'sku_name': i.good.sku_name,
                'title': i.good.title,
                'price': i.good.price,
                "selling_price": i.good.selling_price,
                'img': i.good.img,
            }
            collect_list.append(temp)

        return Response({"code":200, 'msg':'获取收藏商品成功', "collectList":collect_list})

    @check_login
    # 用户删除购物车数据
    def delete(self, request):

        # 1.获取用户对象
        user = request.user

        # 2.获取商品id
        good_id = request.data.get("productID")

        # 3.查询收藏对象, 并删除
        collect_obj = Collect.objects.get(user=user, good_id=good_id)
        collect_obj.delete()

        return Response({'code':200,'msg':'删除收藏成功'})






